import os
import sqlite3
import socket
import hashlib
from bottle import route, run, template, static_file, get, post, request, redirect, response

#m = hashlib.md5()
#m.update("test")
#md5 = m.hexdigest()
#print(md5)

#%for i in range(1,10):
#	{{"templated code"}}
#%end

#request.forms is a dictionary!

conn = sqlite3.connect('scout.db')
c = conn.cursor()

@get('/login')
def login():
	return template('login')

@post('/auth', method='POST')
def check_creds():
	#socket.gethostbyname(socket.gethostname())
	username = request.forms.get('uname')
	password = request.forms.get('pword')
	
	try:
		c.execute('select * from users where username="'+username+'" and password="'+password+'"')
	except:
		redirect("/login")

	if c.fetchone() is None:
		redirect("/login")
	else:
		#successful here!
		#add expires expires a datetime object or unix timestamp
		#change test to md5 of username+password
		
		m = hashlib.md5()
		m.update(username+password)
		cookiemd5val = m.hexdigest()
		
		response.set_cookie("z_auth", cookiemd5val, max_age=6000)
		response.set_cookie("z_name", username, max_age=6000)
		
		redirect("/")
		
	return "Redirecting..."

#add auth require here to certian pages
def auth_require():
	
	try:
		c.execute('select * from users where username="'+request.get_cookie("z_name")+'"')
		m = hashlib.md5()
		arrayvals = c.fetchone()
		us = arrayvals[0]
		pa = arrayvals[1]
		m.update(us+pa)
		cookiemd5 = m.hexdigest()
		
		if(request.get_cookie("z_auth")==cookiemd5):
			return True
		else:
			redirect("/login")
		return False
	except:
		redirect("/login")

@route('/static/:filename')
def server_static(filename):
	return static_file(filename, root=os.getcwd()+'/staticfiles/')

@post('/search', method='GET')
def search():
	return request.GET.get('search')

def index(a,b):
	auth_require();
	#a for highlited nav
	#b for content
	return template('home',cont=b,place=a)
	
#add main pages after this line
@route('/home')
@route('/index')
@route('/')
def root():
	content = '''
	zScouting System V.01 brought to you by Team 537 Charger Robotics! </br>
	Developed By: Zach Geis &copy;
	'''
	return index(1,content)

@route('/teams')
def teams():
	content = "Teams Page"
	return index(2,content)
	
@route('/addmatchdata')
def amd():
	content = "Add Match Data"
	return index(3,content)
	
@route('/printscoutingreport')
def psr():
	content = "Print Scouting Report"
	return index(4,content)
	
#Below this line place all service page related functions
def serviceButtons():
	return  '''
	<div class="buttons">
	<a href="/adduser" class="service">Add User</a></br></br></br>
	<a href="/addteam" class="service">Add Team</a></br></br></br>
	<a href="/addmatch" class="service">Add Match</a></br></br></br>
	<a href="/addcomp" class="service">Add Competition</a></br></br></br>
	</div>
	'''
	
@route('/services')
def services():
	content = serviceButtons()
	return index(5,content)
	
@get('/adduser')
def usercreds():
	content='''
	<form class="serviceform" method="POST" action="/adduser">
	<table class="form">
	<tr><td class="title" colspan="2">Add User</td></tr>
	<tr>
	<td class="section">Username: </td>
	<td class="section"><input type="text" name="uname" /></td>
	</tr>
	<tr>
	<td class="section">Password: </td>
	<td class="section"><input type="password" name="pword" /></td>
	</tr>
	<tr>
	<td class="section">Retype Password: </td>
	<td class="section"><input type="password" name="pword" /></td>
	</tr>
	<tr><td class="section"></td><td class="section"> <div class="buttons"> <button class="positive" type="submit">Create</button></div></td></tr>
	</table>
	</form>
	'''
	content+=serviceButtons()
	return index(5, content)

@post('/adduser', method='POST')
def adduser():
	c.execute("insert into users values ('"+request.forms.get('uname')+"','"+request.forms.get('pword')+"', 'admin')")
	conn.commit()	
	return index(5,"Successful add!")	

@route('/addteam')
def teamcreds():

	c.execute("PRAGMA table_info(teams)")
	dbtables = c.fetchall()
	formtables = []
	print dbtables
	for i in range(len(dbtables)):
		formtables.insert(i,str(dbtables[i][1]))
	
	content=zform("serviceform", "Add Team", formtables, "Create", "POST", "/addteam","Team ").getform()
	content+=serviceButtons()
	return index(5, content)
	
@route('/addteam', method='POST')
def addteam():

	c.execute("PRAGMA table_info(teams)")
	dbtables = c.fetchall()
	formtables = []
	print dbtables
	for i in range(len(dbtables)):
		formtables.insert(i,str(dbtables[i][1]))

	sqlq = "insert into teams values ("
	for i in range(len(request.forms.items())):
		sqlq += "'"+str(request.forms.get(formtables[i]))+"',"
	sqlq = sqlq[0:len(sqlq)-1]+")"
	print str(sqlq)
	c.execute(sqlq)
	conn.commit()
	return sqlq
	
@route('/addmatch')
def matchcreds():

	c.execute("PRAGMA table_info(matches)")
	dbtables = c.fetchall()
	formtables = []
	print dbtables
	for i in range(len(dbtables)):
		formtables.insert(i,str(dbtables[i][1]))
	
	content=zform("serviceform", "Add Match", formtables, "Create", "POST", "/addmatch","").getform()
	content+=serviceButtons()
	return index(5, content)
	
@route('/addmatch', method='POST')
def addmatch():
	c.execute("PRAGMA table_info(matches)")
	dbtables = c.fetchall()
	formtables = []
	print dbtables
	for i in range(len(dbtables)):
		formtables.insert(i,str(dbtables[i][1]))

	sqlq = "insert into matches values ("
	for i in range(len(request.forms.items())):
		sqlq += "'"+str(request.forms.get(formtables[i]))+"',"
	sqlq = sqlq[0:len(sqlq)-1]+")"
	print str(sqlq)
	c.execute(sqlq)
	conn.commit()
	return sqlq
	
@route('/addcomp')
def compcreds():

	c.execute("PRAGMA table_info(comps)")
	dbtables = c.fetchall()
	formtables = []
	print dbtables
	for i in range(len(dbtables)):
		formtables.insert(i,str(dbtables[i][1]))
	
	content=zform("serviceform", "Add Competition", formtables, "Create", "POST", "/addcomp","").getform()
	content+=serviceButtons()
	return index(5, content)
	
@route('/addcomp', method='POST')
def addcomp():
	c.execute("PRAGMA table_info(comps)")
	dbtables = c.fetchall()
	formtables = []
	print dbtables
	for i in range(len(dbtables)):
		formtables.insert(i,str(dbtables[i][1]))

	sqlq = "insert into comps values ("
	for i in range(len(request.forms.items())):
		sqlq += "'"+str(request.forms.get(formtables[i]))+"',"
	sqlq = sqlq[0:len(sqlq)-1]+")"
	print str(sqlq)
	c.execute(sqlq)
	conn.commit()
	return sqlq
	
class zform:
	def __init__(self, txtclass, txttitle, arfield, txtsub, txtmethod, txtaction, prefix):
	
		self.form = ''
		self.form += '<form class="'+txtclass+'" method="'+txtmethod+'" action="'+txtaction+'">'
		self.form +='<table class="form">'
		self.form +='<tr><td class="title" colspan="2">'+txttitle+'</td></tr>'
		
		for i in range(len(arfield)):
			self.form +='<tr>'
			self.form +='<td class="section">'+prefix+arfield[i]+':</td>'
			self.form +='<td class="section"><input type="text" name="'+arfield[i]+'" /></td>'
		
		self.form +='<tr><td class="section"></td><td class="section"> <div class="buttons"> <button class="positive" type="submit">'+txtsub+'</button></div></td></tr>'
		self.form +='</table>'
		self.form +='</form>'
		
	def getform(self):
		return self.form
		
#super early work in progess what ever is before alpha :/
class zTable:
	def __init__(self, ardata, prefix):
	
		self.form = ''
		self.form +='<table class="form">'
		self.form +='<tr><td class="title" colspan="2">'+txttitle+'</td></tr>'
		
		for i in range(len(ardata)):
			self.form +='<tr>'
			self.form +='<td class="section">'+prefix+ardata[i]+':</td>'
			self.form +='<td class="section"><input type="text" name="'+ardata[i]+'" /></td>'
		
		self.form +='</table>'
		
	def gettable(self):
		return self.form
	
@route('/logout')
def logout():
	response.set_cookie("z_auth", "0")
	response.set_cookie("z_name", "0")
	redirect("/login")
	return 0;	

#ip local str(socket.gethostbyname(socket.gethostname()))
run(host='localhost', port=8080)
